package cn.lingyangwl.agile.system.handler.config;

import cn.lingyangwl.agile.common.core.config.*;
import cn.lingyangwl.agile.dynamic.config.core.*;
import cn.lingyangwl.agile.infra.*;
import cn.lingyangwl.agile.infra.common.*;
import cn.lingyangwl.agile.model.constants.*;
import cn.lingyangwl.agile.model.enums.*;
import cn.lingyangwl.agile.model.module.config.param.*;
import cn.lingyangwl.agile.model.module.tenant.*;
import cn.lingyangwl.agile.system.model.entity.*;
import cn.lingyangwl.framework.tool.core.*;
import com.alibaba.fastjson2.JSON;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @author shenguangyang
 */
@Component
public class WxMpConfigHandler extends ConfigHandler {
    @Resource
    private InfraApi infraApi;
    @Resource
    private GlobalProperties properties;
    @Resource
    private ConfigFactory configFactory;

    @Override
    public void doneWriteOps(SysConfig newConfig, BaseConfigParam<?> param) {
        WxMpParam wxMpParam = (WxMpParam) param;

        if (StringUtils.isEmpty(wxMpParam.getQrCodeUrl()) && Objects.nonNull(newConfig.getId())) {
            // 获取微信公众号二维码, 扫码获取openId
            // 当用户扫码之后, 会在 infra 服务中收到微信服务器的推送扫码事件, 然后由infra服务将数据推送到push服务最终通过websocket返回给前端
            ScanScene scanScene = ScanScene.builder().isRefresh(true).sceneCode(QrCodeSceneEnum.DEFAULT.getCode()).build();
            String qrcode = infraApi.getMpQrcode(scanScene);
            wxMpParam.setQrCodeUrl(qrcode);
        }
        newConfig.setConfigValue(JSON.toJSONString(wxMpParam));
    }

    @Override
    protected BaseConfigParam<?> doneReadOps(BaseConfigParam<?> param) {
        WxMpParam wxMpParam = (WxMpParam) param;
        wxMpParam = Optional.ofNullable(wxMpParam).orElse(new WxMpParam());
        String tenantId = TenantContext.get().getTenantId();

        String url = UrlUtils.removeRepeatSlashOfUrl(
                properties.getServerAddr() + "/" + ServiceCodeCons.INFRA_SERVICE + InfraCons.URL_WX_MP_PUSH + "/" + tenantId
        );
        wxMpParam.setMsgPushUrl(url);
        return wxMpParam;
    }

    @Override
    public ConfigKeyEnum configKey() {
        return ConfigKeyEnum.WX_MP;
    }
}
